// useDebounceEffect.ts
import { watch, onBeforeUnmount, Ref } from 'vue'

export function useDebounceEffect<T>(
  source: Ref<T>,
  effect: (val: T) => void,
  delay = 500
) {
  let timer: ReturnType<typeof setTimeout> | null = null

  watch(
    source,
    (newVal) => {
      if (timer) clearTimeout(timer)
      timer = setTimeout(() => {
        effect(newVal)
      }, delay)
    },
    { immediate: false }
  )

  onBeforeUnmount(() => {
    if (timer) clearTimeout(timer)
  })
}
